package cn.wolfcode.trip.base.util.websocket;

//import cn.wolfcode.trip.base.domain.Message;

import cn.wolfcode.trip.base.domain.ChatMessage;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.ChatMessageMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 * WebSocketServiceImpl class
 *
 * @author lishuanwang
 * @date 2019/5/31
 */
@Service
public class WebSocketService {

    @Autowired
    private ChatMessageMapper chatMessageMapper;
    private Logger logger = LoggerFactory.getLogger(WebSocketService.class);
    //声明websocket连接类
    private Websocket websocket = new Websocket();
//    @Autowired
//    private IMessageService messageService;
    /**
     * @Title: sendToAllTerminal
     * @Description: 调用websocket类给用户下的所有终端发送消息
     * @param @param userId 用户id
     * @param @param message 消息
     * @param @return 发送成功返回true，否则返回false
     */
    public Boolean sendToAllTerminal(Long userId, Long receiverId, String message) {
        logger.debug("向用户{}的消息：{}",receiverId,message);
        ChatMessage chatMessage = new ChatMessage();
        User sender = new User();
        sender.setId(userId);
        User receiver = new User();
        receiver.setId(receiverId);
        chatMessage.setContent(message);
        chatMessage.setSender(sender);
        chatMessage.setReceiver(receiver);
        logger.debug("向用户{}的消息：{}",userId,message);
        if(websocket.sendMessage(receiverId,message)){
            chatMessage.setStatus(true);
            chatMessageMapper.insert(chatMessage);
            return true;
        }else{
            chatMessageMapper.insert(chatMessage);
            return false;
        }
    }
}
